package tgc.edu.exam.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.custom.VerifyCodeUtils;
import tgc.edu.exam.entity.Student;
import tgc.edu.exam.entity.SysFile;
import tgc.edu.exam.entity.SysRole;
import tgc.edu.exam.entity.SysUser;
import tgc.edu.exam.entity.TbClass;
import tgc.edu.exam.entity.TbMenu;
import tgc.edu.exam.entity.Teacher;
import tgc.edu.exam.security.UserUtils;
import tgc.edu.exam.service.MenuService;
import tgc.edu.exam.service.StudentService;
import tgc.edu.exam.service.SysFileService;
import tgc.edu.exam.service.SysRoleService;
import tgc.edu.exam.service.SysUserService;
import tgc.edu.exam.service.TbClassService;
import tgc.edu.exam.web.form.RegisterForm;
import tgc.edu.exam.web.form.RegisterForm2;

@Controller
public class IndexController {
	@Autowired
	private TbClassService tbClassDAO;
	@Autowired
	private SysUserService userservice;
	@Autowired
	private StudentService studentservice;
	@Autowired
	private SysFileService fileservice;
	@Autowired
	private TbClassService tbClassService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private SysUserService userService;
	@Value("${web.upload-path}")
    private String path;
	@RequestMapping(value = { "/login", "/" }, method = RequestMethod.GET)
	public String login(ModelMap map) {
		File pat=new File("d:\\jeecgs");
		if(!pat.isDirectory()) {
			pat.mkdir();
		}
		String uuid = UUID.randomUUID().toString();
		VerifyCodeUtils code = new VerifyCodeUtils(160, 40, 4, 150);
		String path = "d:/jeecgs/" + uuid + ".png";
		try {
			System.out.println(code.getCode() + " >" + path);
			code.write(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		map.put("code", code.getCode());
		map.put("uuid", uuid);
		return "main/login";
	}

	@RequestMapping(value = "/verify")
	@ResponseBody
	public Object Verify() {
		Map<String, String> map = new HashMap<>();
		String uuid = UUID.randomUUID().toString();
		VerifyCodeUtils code = new VerifyCodeUtils(160, 40, 4, 150);
		String path = "d:/jeecgs/" + uuid + ".png";
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("\"code\":\"" + code.getCode() + "\",");
		sb.append("\"uuid\":\"" + uuid + "\"");
		sb.append("}");
		JSONObject result = JSONObject.parseObject(sb.toString()); 
		String data = result.toJSONString(); 
		try {
			System.out.println(code.getCode() + " >" + path);
			code.write(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

	@RequestMapping(value = "/verifyCode")
	@ResponseBody
	private void VerifyCode(String uuid, HttpServletRequest request, HttpServletResponse response) {
		String filename = uuid + ".png";
		filename = getStr(request, filename);
		File file = new File("d:/jeecgs/" + uuid + ".png");
		if (file.exists()) {
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				response.setContentType("application/x-msdownload");
				response.addHeader("Content-Disposition", "attachment; filename=" + filename);
				ServletOutputStream out = response.getOutputStream();
				byte[] buf = new byte[2048];
				int n = 0;
				while ((n = fis.read(buf)) != -1) {
					out.write(buf, 0, n);
				}
				fis.close();
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private String getStr(HttpServletRequest request, String fileName) {
		String downloadFileName = null;
		// 仅提供了部分代码，因为我们已经明确问题的所在，知道修改那一部分了，（代码中downloadFileName 即代表
		// *=utf-8'zh_cn'文件名.xx部分）
		String agent = request.getHeader("USER-AGENT");
		try {
			if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
				// downloadFileName = "=?UTF-8?B?" + (new
				// String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
				// 设置字符集
				downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
			} else {
				downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return downloadFileName;
	}

	@RequestMapping(value = "/xybm")
	public String main() {
		return "main/xybm";
	}

	@RequestMapping(value = "/main1")
	public String main1(ModelMap map) {
		List<TbMenu> menus=menuService.findAuditMenu();
		map.put("menus",menus);
		if(menus.isEmpty()) {
			return "main/main1";
		}
		return "main/main";
	}

	@RequestMapping(value = "/test")
	public String test() {
		return "main/test";
	}

	@RequestMapping(value = "/loginXy")
	public String loginXy() {
		return "main/login-xy";
	}

	/***
	 * 跳转学员报名页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/goXybm")
	public String goXybm() {
		return "main/xybm";
	}

	/***
	 * 学员注册 账号为身份证号码 密码为身份证后6位
	 * 
	 * @param form
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/toXybmsave")
	public Object toXybmsave(RegisterForm form, ModelMap map) {

		SysUser ifusernull = userservice.findByUsername(form.getIdcode());
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		if (ifusernull == null && form.getName() != null && form.getIdcode() != null) {

			Student studententity = new Student();
			String pwd = form.getIdcode();
			String password = pwd.substring(pwd.length() - 6, pwd.length());
			studententity.setUsername(form.getIdcode());
			studententity.setPassword(encoder.encode(password));

			SysRole findbyCode = sysRoleService.findbyCode("ROLE_STUDENT");
			System.out.println(findbyCode.getCode());
			studententity.getRoles().add(findbyCode);
			TbClass tbclassEntity = tbClassService.findById(UUID.fromString(form.getTbClassNmae()));
			studententity.setTbClass(tbclassEntity);
			BeanUtils.copyProperties(form, studententity, "id");
			studentservice.saves(studententity);
			fileservice.DeleteAll(form.getFileuuid());
			map.put("username", form.getIdcode());
			map.put("password", password);
			return "main/registeredsuccessfully";
		} else {
			map.put("hint", "注册失败，此用户已存在，无需重复注册");
			return "main/xybm";
		}
	}

	/***
	 * 注册 用户上传图片
	 * 
	 * @param file
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/toFilesave")
	@ResponseBody
	private Object toFilesave(MultipartFile file, ModelMap map) {
		String uuid = UUID.randomUUID().toString();
		boolean boole = fileservice.savefile(file, uuid);
		if (boole) {
			return new AjaxResult(true, uuid);
		} else {
			return new AjaxResult(true, file.getOriginalFilename());
		}

	}
	
	@RequestMapping(value = "/updat1")
	@ResponseBody
	private Object updat1(MultipartFile file) {
		String filename = file.getOriginalFilename();
		String uuid = UUID.randomUUID().toString();
		boolean boole = fileservice.savefile(file, uuid);
		SysFile file2 = fileservice.findByUuid(uuid);
		file2.setIsUsed(true);
		fileservice.save(file2);
		if (boole) {
			Map<String,Object> map = new HashMap<String,Object>();
			Map<String,Object> map2 = new HashMap<String,Object>();
			map.put("code", 0);
			map.put("msg","上传成功");
			map2.put("src", path+"download?uuid="+uuid);
			map2.put("title", filename);
			map.put("data", map2);
			return map;
		} else {
			return new AjaxResult(true, file.getOriginalFilename());
		}

	}

	/***
	 * 下载图片
	 * 
	 * @param uuid
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/download")
	@ResponseBody
	private void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
		fileservice.download(uuid, request, response);
	}

	/***
	 * 注册 主体班学员 专题班学员
	 * 
	 * @param value
	 * @return
	 */
	@RequestMapping(value = "/totbClass")
	@ResponseBody
	private Object tbClass(String value) {
		List<TbClass> tbclasslist = tbClassService.findByTbClassName(value);

		List<RegisterForm2> tb = new ArrayList<>();
		for (TbClass tbClass : tbclasslist) {
			boolean ifTime = tbClassService.ifTime(tbClass);// 判断当前的时间
			if (ifTime) {
				RegisterForm2 res = new RegisterForm2();
				res.setId(tbClass.getId());
				res.setName(tbClass.getName());
				tb.add(res);
			}
		}
		return tb;
	}

	@RequestMapping(value = "/toTime")
	@ResponseBody
	private Object TbClassTime(String uuid) {
		String list = tbClassService.findByTime(UUID.fromString(uuid));
		return list;
	}
	
	@RequestMapping(value="/view")
	public String view(ModelMap map) {
		SysUser user = userUtils.getUser();
		Teacher model=(Teacher) user;
		map.put("model", model);
		return "teacher/view";
	}
	
	@RequestMapping(value="/changePwd",method=RequestMethod.GET)
	public String changePwd() {
		return "main/changePwd";
	}
	
	@RequestMapping(value="/changePwd",method=RequestMethod.POST)
	@ResponseBody
	public Object changePwd(String oldPwd,String newPwd) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		SysUser user = userUtils.getUser();
		String password = user.getPassword();
		if(!encoder.matches(oldPwd, password)) {
			return new AjaxResult(false, "旧密码不正确！");
		}
		user.setPassword(encoder.encode(newPwd));
		userService.save(user);
		return new AjaxResult("密码修改成功");
	}
	
	
}
